<template>
  <view class="chat-item" :class="active ? 'active' : ''">
    <!--rich-text中的表情包会屏蔽事件，所以这里用一个遮罩层捕获点击事件 -->
    <view class="mask" @tap="showChatBox()"></view>
    <view class="left">
      <head-image :url="chat.headImage" :name="chat.showName"></head-image>
    </view>
    <view class="chat-right">
      <view class="chat-name">
        <view class="chat-name-text">
          <view>{{ chat.showName }}</view>
          <uni-tag v-if="chat.type == 'GROUP'" circle size="small" text="群" type="primary"></uni-tag>
          <uni-tag v-if="chat.type == 'SYSTEM'" circle text="官方" size="small" type="error"></uni-tag>
        </view>
        <view class="chat-time">{{ $date.toTimeText(chat.lastSendTime, true) }}</view>
      </view>
      <view class="chat-content">
        <view class="chat-at-text">{{ atText }}</view>
        <view class="chat-send-name" v-if="isShowSendName">{{ chat.sendNickName }}</view>
        <rich-text class="chat-content-text" :nodes="$emo.transform(chat.lastContent, 'emoji-small')"></rich-text>
        <uni-badge v-if="chat.unreadCount > 0" :max-num="99" :text="chat.unreadCount" />
      </view>
    </view>
  </view>
</template>

<script>
import { mapStores } from "pinia";
import chatStore from "@/store/chatStore.js";
import LZString from 'lz-string';

export default {
  name: "chatItem",
  data() {
    return {
      isJumping: false
    }
  },
  props: {
    chat: {
      type: Object,
    },
    index: {
      type: Number,
    },
    active: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    ...mapStores(chatStore),
    isShowSendName() {
      if (!this.chat.sendNickName) {
        return false;
      }
      let size = this.chat.messages.length;
      if (size == 0) {
        return false;
      }
      // 只有群聊的普通消息需要显示名称
      let lastMsg = this.chat.messages[size - 1];
      return this.$msgType.isNormal(lastMsg.type);
    },
    atText() {
      if (this.chat.atMe) {
        return "[有人@我]";
      } else if (this.chat.atAll) {
        return "[@全体成员]";
      }
      return "";
    },
  },
  methods: {
    showChatBox() {
      console.log("showChatBox called", this.chat);

      // 防止重复点击
      if (this.isJumping) {
        console.log("正在跳转中，请勿重复点击");
        return;
      }

      // 初始化期间进入会话会导致消息不刷新
      if (!getApp().$vm.isInit || this.chatStore.isLoading()) {
        uni.showToast({
          title: "正在初始化页面,请稍后...",
          icon: "none"
        });
        return;
      }

      // 显示加载中提示
      // uni.showLoading({
      // 	title: '页面加载中...',
      // 	mask: true
      // });

      this.isJumping = true;

      // 获取token和userId，先检查是否存在
      const accessToken = uni.getStorageSync("loginInfo").accessToken || '';
      const userId = uni.getStorageSync("userId") || '';

      if (!accessToken || !userId) {
        uni.hideLoading();
        this.isJumping = false;
        uni.showToast({
          title: "登录信息已失效，请重新登录",
          icon: 'none'
        });
        return;
      }

      let url = '';
      if (this.chat.type == 'SYSTEM') {
        url = `/pages/chat/chat-system?targetId=${this.chat.targetId}&accessToken=${accessToken}&userId=${userId}`;
      } else {
        url = `/pages/chat/chat-box?targetId=${this.chat.targetId}&accessToken=${accessToken}&userId=${userId}`;
      }

      // console.log(uni.getStorageSync("loginInfo"));
      // // 创建本地变量而不是直接修改prop
      // const chatWithLoginInfo = { ...this.chat, ...uni.getStorageSync("loginInfo") }
      // let jsonString = JSON.stringify(chatWithLoginInfo);
      // let compressedJson = LZString.compressToEncodedURIComponent(jsonString);
      // console.log(compressedJson);

      // let url = '';
      // if (this.chat.type == 'SYSTEM') {
      //   url = `/pages/chat/chat-system?data=${compressedJson}`;
      // } else {
      //   url = `/pages/chat/chat-box?data=${compressedJson}`;
      // }
      // uni.navigateTo({ url: url })
      // uni.hideLoading();
      // return

      // 完整URL (用于原生跳转)
      const fullUrl = `https://www.yaozhuasocial.com/yaozhua_w/#${url}`;

      console.log("准备跳转到URL:", fullUrl);

      // 使用原生应用的跳转方法
      const platform = uni.getSystemInfoSync().platform;
      // console.log("当前平台:", platform);

      try {
        switch (platform) {
          case "android":
            if (window.AndroidBridge) {
              let data = {
                hideNavBar: "0",
                hideTotalNavBar: "1",
                hideBottomSafeBar: "1",
                url: fullUrl
              };
              let jsonStr = JSON.stringify(data);
              console.log("Android跳转参数:", jsonStr);
              window.AndroidBridge.pushNewWebVC(jsonStr);
              console.log("Android跳转已执行");

              // 延迟隐藏加载提示，避免感觉卡顿
              setTimeout(() => {
                uni.hideLoading();
                this.isJumping = false;
              }, 500);
            } else {
              console.log("AndroidBridge不存在");
              uni.hideLoading();
              this.isJumping = false;
            }
            break;
          case "ios":
            if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.pushNewWebVC) {
              let data = {
                hideNavBar: "0",
                hideTotalNavBar: "1",
                hideBottomSafeBar: "1",
                url: fullUrl
              };
              console.log("iOS跳转参数:", data);
              window.webkit.messageHandlers.pushNewWebVC.postMessage(data);
              console.log("iOS跳转已执行");

              // 延迟隐藏加载提示，避免感觉卡顿
              setTimeout(() => {
                uni.hideLoading();
                this.isJumping = false;
              }, 500);
            } else {
              console.log("webkit桥接不存在");
              uni.hideLoading();
              this.isJumping = false;
            }
            break;
          default:
            console.log("运行在开发者工具上");
            uni.hideLoading();
            this.isJumping = false;
            break;
        }
      } catch (error) {
        console.error("跳转出错:", error);
        uni.hideLoading();
        this.isJumping = false;
        uni.showToast({
          title: "跳转失败，请重试",
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
.chat-item {
  display: flex;
  position: relative;
  padding: 0 20rpx;
  align-items: center;
  background-color: white;
  white-space: nowrap;
  width: 92vw;
  margin: 0 auto;
  height: 168rpx;
  border-radius: 16rpx;
  padding: 0 32rpx;
  margin-bottom: 16rpx;

  &:active {
    background-color: $im-bg-active;
  }

  &.active {
    background-color: $im-bg-active;
  }

  .mask {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    right: 0;
    z-index: 99;
  }

  .left {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 104rpx;
    height: 104rpx;
  }

  .chat-right {
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 20rpx;
    text-align: left;
    overflow: hidden;

    .chat-name {
      display: flex;

      .chat-name-text {
        flex: 1;
        font-size: $im-font-size-large;
        white-space: nowrap;
        overflow: hidden;
        display: flex;
        align-items: center;
        font-weight: 600;
        color: #44496a;

        .uni-tag {
          text-align: center;
          font-size: 16rpx;
          margin-left: 3rpx;
          opacity: 0.8;
        }
      }

      .chat-time {
        font-size: $im-font-size-smaller-extra;
        color: $im-text-color-lighter;
        text-align: right;
        white-space: nowrap;
        overflow: hidden;
      }
    }

    .chat-content {
      display: flex;
      font-size: $im-font-size-smaller;
      color: $im-text-color-lighter;
      padding-top: 8rpx;
      align-items: center;
      font-size: 28rpx;
      color: #8e8e92;

      .chat-at-text {
        color: $im-color-danger;
      }

      .chat-send-name {
        font-size: $im-font-size-smaller;
      }

      .chat-content-text {
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>